/*
 * AddProductServlet.java
 * 作用：处理用户发布新商品的请求，包括商品信息提交和图片上传。
 */
package com.campustradingwall.controller.user;

import com.campustradingwall.dao.ProductDao;
import com.campustradingwall.model.Product;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Paths;

@WebServlet("/user/addProduct")
@MultipartConfig
public class AddProductServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("user");

        String name = request.getParameter("name");
        BigDecimal price = new BigDecimal(request.getParameter("price"));
        String description = request.getParameter("description");
        Part filePart = request.getPart("image");

        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        String uniqueFileName = user.getId() + "_" + System.currentTimeMillis() + "_" + fileName;
        String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads" + File.separator + "product_images";

        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        filePart.write(uploadPath + File.separator + uniqueFileName);

        Product product = new Product();
        product.setUserId(user.getId());
        product.setName(name);
        product.setPrice(price);
        product.setDescription(description);
        product.setImageUrl(uniqueFileName);
        product.setStatus("on_shelf"); // 默认上架

        productDao.addProduct(product);

        response.sendRedirect(request.getContextPath() + "/user/products");
    }
} 